package com.thread.resource.sharing.danger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class EvenChecker implements Runnable {

	private IntGenerator generator;
	private final int id;

	public EvenChecker(IntGenerator g, int ident) {
		generator = g;
		id = ident;
		System.out.println("id:" + id + "初始化");
	}

	@Override
	public void run() {
		System.out.println("id:" + id + "开始执行");

		while (!generator.isCancel()) {
			int val = generator.next();
			// 检查是否是偶数
			if (val % 2 != 0) {
				System.out.println("id:" + id + "," + val + "不是偶数！");
				generator.cancel();// 取消后续检查
			}
		}
	}

	public static void test(IntGenerator gp, int count) {
		System.out.println("Press Control-C to exit");
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < count; i++) {
			exec.execute(new EvenChecker(gp, i));
		}
		exec.shutdown();
		System.out.println("结束");
	}

	public static void test(IntGenerator gp) {
		test(gp, 10);
	}

}
